package com.xinqi.modules.sys.gpt.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.core.constant.GptConstants;
import com.xinqi.common.core.utils.MessageUtils;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.modules.sys.gpt.convert.ShareQuotaConvert;
import com.xinqi.modules.sys.gpt.domain.DayCountEntity;
import com.xinqi.modules.sys.gpt.domain.ShareQuotaEntity;
import com.xinqi.modules.sys.gpt.dto.req.ShareQuotaCreateDTO;
import com.xinqi.modules.sys.gpt.dto.req.ShareQuotaQueryDTO;
import com.xinqi.modules.sys.gpt.dto.req.ShareQuotaUpdateDTO;
import com.xinqi.modules.sys.gpt.dto.rsp.ShareQuotaResultDTO;
import com.xinqi.modules.sys.gpt.manager.DayCountManager;
import com.xinqi.modules.sys.gpt.manager.ShareQuotaManager;
import com.xinqi.modules.sys.gpt.service.ShareQuotaService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 邀请规则表服务层实现
 *
 * @author: yyzhen
 * @date: 2023/05/23
 */
@Validated
@Service("shareQuotaService")
@RequiredArgsConstructor
public class ShareQuotaServiceImpl implements ShareQuotaService {
    private final ShareQuotaConvert shareQuotaConvert;
    private final ShareQuotaManager shareQuotaManager;

    private final DayCountManager dayCountManager;

    /**
     * 分页查询 邀请规则表数据
     */
    @Override
    @DS("slaver")
    public PageInfo<ShareQuotaResultDTO> page(Param pageable, ShareQuotaQueryDTO query) {
        IPage<ShareQuotaEntity> page = shareQuotaManager.findPage(Pages.page(pageable), query);
        return Pages.convert(page, shareQuotaConvert::convert);
    }

    /**
     * 查询 邀请规则表数据
     */
    @Override
    public List<ShareQuotaResultDTO> list(Long userId) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(userId), MessageUtils.message("user.id.not.black"));
        List<ShareQuotaResultDTO> result = shareQuotaManager.findList(new ShareQuotaQueryDTO()).stream()
            .map(shareQuotaConvert::convert).collect(Collectors.toList());
        //根据次数正序排序
        Comparator<ShareQuotaResultDTO> comparator = Comparator.comparing(ShareQuotaResultDTO::getShareCount);
        result.sort(comparator);
        //获取分享成功次数
        DayCountEntity count = dayCountManager.findByUser(userId);
        //是否达到判断
        Integer shareCount = 0;
        if (Objects.nonNull(count)) {
            shareCount = count.getShareCount();
        }
        //规则总计可用次数
        Integer availableCount = GptConstants.DEFAULT_QUOTA;
        for (int i = 0; i < result.size(); i++) {
            ShareQuotaResultDTO item = result.get(i);
            availableCount += result.get(i).getShareQuota();
            item.setAvailableCount(new Integer(availableCount));
            item.setIsAchieve(shareCount >= item.getShareCount() ? YesNoNumberEnum.YES.getCode() : YesNoNumberEnum.NO.getCode());
        }

        return result;
    }

    /**
     * 根据id查询 邀请规则表数据
     */
    @Override
    public ShareQuotaResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), MessageUtils.message("gpt.share.quota.id.not.blank"));
        return Optional.ofNullable(shareQuotaManager.getById(id)).map(shareQuotaConvert::convert).orElse(null);
    }

    /**
     * 新增 邀请规则表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(ShareQuotaCreateDTO dto) {
        ShareQuotaEntity count = shareQuotaManager.findByCount(dto.getShareCount());
        CommonErrors.BAD_REQUEST.check(Objects.isNull(count), MessageUtils.message("gpt.share.quota.shareCount.is.existence"));
        ShareQuotaEntity entity = shareQuotaConvert.create(dto);
        shareQuotaManager.save(entity);

        return entity.getId();
    }

    /**
     * 根据id修改 邀请规则表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(ShareQuotaUpdateDTO dto) {
        ShareQuotaEntity old = Optional.ofNullable(shareQuotaManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException(MessageUtils.message("data.does.not.exist")));
        ShareQuotaEntity count = shareQuotaManager.findByCount(dto.getShareCount());
        if (Objects.nonNull(count)) {
            CommonErrors.BAD_REQUEST.check(Objects.equals(count.getId(), dto.getId()), MessageUtils.message("gpt.share.quota.shareCount.is.existence"));
        }
        ShareQuotaEntity entity = shareQuotaConvert.update(dto);
        return shareQuotaManager.updateById(entity);
    }

    /**
     * 根据id删除 邀请规则表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), MessageUtils.message("gpt.share.quota.id.not.blank"));
        return shareQuotaManager.removeById(id);
    }

}
